// address.js
const app = getApp()

Page({
  data: {
    addresses: [],
    loading: false,
    userInfo: {
      isLogin: false
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.loadAddresses()
  },

  onShow() {
    this.loadAddresses()
  },

  // 加载用户信息
  loadUserInfo() {
    const globalUserInfo = app.getUserInfo()
    this.setData({ userInfo: globalUserInfo })
  },

  // 加载地址数据
  loadAddresses() {
    if (!this.data.userInfo.isLogin) {
      this.setData({ addresses: [] })
      return
    }

    this.setData({ loading: true })
    this.getAddressesFromAPI()
  },

  // 从API获取地址数据
  getAddressesFromAPI() {
    wx.request({
      url: 'http://localhost:8082/user/addresses',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        this.setData({ loading: false })
        
        if (res.data && res.data.code === 200) {
          const addresses = (res.data.data.addresses || []).map(address => ({
            id: address.id,
            name: address.receiver,
            phone: address.phone,
            province: address.province,
            city: address.city,
            district: address.district,
            detail: address.detailAddress,
            isDefault: address.isDefault == 1 || address.isDefault === true,
            createTime: this.formatTime(address.createTime)
          }))
          
          // 默认地址置顶排序
          const sortedAddresses = this.sortAddressesWithDefaultFirst(addresses)
          
          this.setData({ addresses: sortedAddresses })
        } else {
          // API失败时显示空状态
          this.setData({ 
            loading: false,
            addresses: []
          })
        }
      },
      fail: (err) => {
        console.error('获取地址数据失败:', err)
        // 显示空状态
        this.setData({ 
          loading: false,
          addresses: []
        })
      }
    })
  },

  // 地址排序：默认地址置顶
  sortAddressesWithDefaultFirst(addresses) {
    return addresses.sort((a, b) => {
      // 默认地址排在前面
      if (a.isDefault && !b.isDefault) return -1
      if (!a.isDefault && b.isDefault) return 1
      
      // 如果都是默认地址或都不是默认地址，按创建时间倒序排列
      return new Date(b.createTime) - new Date(a.createTime)
    })
  },


  // 添加地址
  onAddAddress() {
    wx.navigateTo({
      url: '/pages/address-edit/address-edit'
    })
  },

  // 编辑地址
  onEditAddress(e) {
    const address = e.currentTarget.dataset.address
    if (!address) return
    
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?id=${address.id}`
    })
  },

  // 删除地址
  onDeleteAddress(e) {
    const address = e.currentTarget.dataset.address
    if (!address) return
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${address.name}"的地址吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteAddressFromAPI(address.id)
        }
      }
    })
  },

  // 从API删除地址
  deleteAddressFromAPI(addressId) {
    wx.request({
      url: 'http://localhost:8082/user/addresses/delete',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: { id: addressId },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const addresses = this.data.addresses.filter(item => item.id !== addressId)
          this.setData({ addresses })
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data?.message || '删除失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('删除地址失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 设置默认地址
  onSetDefault(e) {
    const address = e.currentTarget.dataset.address
    if (!address) return
    
    if (address.isDefault) {
      this.cancelDefaultAddress(address)
      return
    }
    
    const hasDefault = this.data.addresses.some(item => item.isDefault)
    if (hasDefault) {
      wx.showModal({
        title: '确认更换',
        content: '您已有一个默认地址，是否将其更换为新的默认地址？',
        success: (res) => {
          if (res.confirm) {
            this.setDefaultAddressFromAPI(address.id)
          }
        }
      })
    } else {
      this.setDefaultAddressFromAPI(address.id)
    }
  },

  // 从API设置默认地址
  setDefaultAddressFromAPI(addressId) {
    wx.request({
      url: 'http://localhost:8082/user/addresses/setDefault',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: { id: addressId },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const addresses = this.data.addresses.map(item => ({
            ...item,
            isDefault: item.id === addressId
          }))
          // 重新排序，确保默认地址置顶
          const sortedAddresses = this.sortAddressesWithDefaultFirst(addresses)
          this.setData({ addresses: sortedAddresses })
          wx.showToast({
            title: '设置成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data?.message || '设置失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('设置默认地址失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 取消默认地址
  cancelDefaultAddress(address) {
    wx.showModal({
      title: '确认取消',
      content: `确定要取消"${address.name}"的默认地址设置吗？`,
      success: (res) => {
        if (res.confirm) {
          this.cancelDefaultAddressFromAPI(address.id)
        }
      }
    })
  },

  // 从API取消默认地址
  cancelDefaultAddressFromAPI(addressId) {
    wx.request({
      url: 'http://localhost:8082/user/addresses/cancelDefault',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: { id: addressId },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const addresses = this.data.addresses.map(item => ({ ...item, isDefault: false }))
          // 重新排序
          const sortedAddresses = this.sortAddressesWithDefaultFirst(addresses)
          this.setData({ addresses: sortedAddresses })
          wx.showToast({
            title: '取消成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data?.message || '取消默认地址失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('取消默认地址失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 去登录
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadAddresses()
    wx.stopPullDownRefresh()
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    
    try {
      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    } catch (e) {
      console.error('时间格式化失败:', e)
      return timeStr
    }
  }
})